import { getToken } from "../utils/auth";
import { Navigate } from "react-router-dom";
import { check } from "../api/login";
import { useEffect } from "react";

import { useDispatch } from "react-redux";
import { setUser } from "../store/modules/userStore";

const AuthRouter = (props) => {
  const dispatch = useDispatch();

  useEffect(() => {
    const fetchCheck = async () => {
      const res = await check();
      if (res.result === 0) {
        dispatch(setUser(res.data.user));
      } else {
        return <Navigate to={"/login"}></Navigate>;
      }
    };
    fetchCheck();
  },[]);
  //做一个同步处理
  const token = getToken();
  if (token) {
    return <>{props.children}</>;
  } else {
    //跳转到登录页面
    return <Navigate to={"/login"}></Navigate>;
  }
};

export default AuthRouter;
